package com.dave.admin.component.log;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dave.admin.component.SpringContextHolder;
import com.dave.admin.modular.boss.entity.WebLog;
import com.dave.admin.util.SecurityUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 每个信息都打印一行，在高并发请求下确实会出现请求之间打印日志串行的问题
 * <p>
 *
 * @author Dave
 */
@Component
@Aspect
@Order(1)
public class RequestLogAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(RequestLogAspect.class);


    @Around("@annotation(sysLog)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, SysLog sysLog) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object result = proceedingJoinPoint.proceed();
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setTitle(sysLog.value());
        requestInfo.setIp(request.getRemoteAddr());
        requestInfo.setUrl(request.getRequestURL().toString());
        requestInfo.setMethod(request.getMethod());
        requestInfo.setUri(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
                proceedingJoinPoint.getSignature().getName()));
        requestInfo.setParameter(JSONUtil.toJsonStr(getRequestParamsByJoinPoint(proceedingJoinPoint)));
        requestInfo.setSpendTime((System.currentTimeMillis() - start) / 1000);
        String urlStr = request.getRequestURL().toString();
        requestInfo.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        requestInfo.setResult(JSONUtil.toJsonStr(result));
        LOGGER.debug("Request Info      : {}", JSONUtil.toJsonStr(requestInfo));

        WebLog webLog = BeanUtil.toBean(requestInfo, WebLog.class);
        webLog.setCreator(SecurityUtil.getUserAdmin().getUsername());
        webLog.setUpdater(SecurityUtil.getUserAdmin().getUsername());
        webLog.setCreateTime(LocalDateTime.now());
        webLog.setUpdateTime(LocalDateTime.now());
        //异步记录
        SpringContextHolder.publishEvent(new LogEvent(webLog));
        return result;
    }


    /**
     * 获取入参
     *
     * @param proceedingJoinPoint
     * @return
     */
    private Map<String, Object> getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = proceedingJoinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = joinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            //如果是文件对象 获取文件名
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();
            }
            //如果是分页对象
            if (value instanceof IPage) {
                value = new JSONObject().put("current", ((IPage) value).getCurrent()).put("size", ((IPage) value).getSize());
            }
            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }


}